package com.wusuowei.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.wusuowei.common.annotation.Log;
import com.wusuowei.common.constant.BusinessTypeEnum;
import com.wusuowei.common.constant.CacheConstants;
import com.wusuowei.common.core.RedisCache;
import com.wusuowei.common.model.po.ComLoginLog;
import com.wusuowei.common.utils.R;
import com.wusuowei.common.utils.StringUtils;
import com.wusuowei.system.model.vo.PageOnlineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统访问记录 前端控制器
 * </p>
 *
 * @author LGY
 */
@Slf4j
@RestController
//@Api(value = "管理接口",tags = "管理接口")
@RequestMapping("system/monitor/online")
public class SysOnlineController {


    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("hasAnyAuthority('monitor:online:list','monitor:online:query')")
    @GetMapping("/page")
    public R findPage(PageOnlineVo pagequery) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<ComLoginLog> userOnlineList = new ArrayList<ComLoginLog>();
        for (String key : keys) {
            ComLoginLog logininfor = redisCache.getCacheObject(key);
            userOnlineList.add(logininfor);
        }
        Collections.reverse(userOnlineList);
        List<ComLoginLog> collect = userOnlineList.stream().filter(item -> {
            boolean f1 = true, f2 = true;
            if (StringUtils.isNotBlank(pagequery.getLocaltion())) {
                f1 = pagequery.getLocaltion().equals(item.getLoginLocation());
            }
            if (StringUtils.isNotBlank(pagequery.getUserName())) {
                f2 = pagequery.getUserName().equals(item.getUserName());
            }
            return f1 & f2;
        }).collect(Collectors.toList());
        List<ComLoginLog> list = CollectionUtil.sub(collect, (pagequery.getPageNum() - 1) * pagequery.getPageSize(), pagequery.getPageNum() * pagequery.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("total", userOnlineList.size());
        map.put("records", list);
        return R.ok().setData(map);
    }

    @PreAuthorize("hasAuthority('monitor:online:quit')")
    @Log(title = "在线用户", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{uid}")
    public R delete(@PathVariable String uid) {
        redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + uid);
        redisCache.deleteObject(CacheConstants.ACCESS_TOKEN_KEY + uid);
        return R.ok();
    }

}
